﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 傻B代码生成器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnConn_Click(object sender, EventArgs e)
        {
            ConnetSQL();
        }


        

        private void btnModel_Click(object sender, EventArgs e)
        {
            foreach (string name in clbTable.CheckedItems)
            {
                CreateModel(name);
            }
        }

        private void btnDAL_Click(object sender, EventArgs e)
        {
            foreach (string tableName in clbTable.CheckedItems)
            {
                CreateDAL(tableName);
            }
        }

        #region 1.生成Model实体类代码   private void CreateModel(string name)
        /// <summary>
        /// 生成Model实体类代码
        /// </summary>
        /// <param name="name"></param>
        private void CreateModel(string name)
        {
            string connStr = txtConnStr.Text;
            string sql = "select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@name";
            DataTable res = SqlHelper.ExecuteDataTable(connStr, sql,
                new SqlParameter("@name", name));
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("class " + name+"Model");
            sb.AppendLine("{");
            foreach (DataRow row in res.Rows)
            {
                string cloName = (string)row["COLUMN_NAME"];
                string dataType = ToDataType((string)row["DATA_TYPE"]);
                sb.AppendLine("public " + dataType + " " + cloName + " {set;get;}");
            }
            sb.AppendLine("}");
            //MessageBox.Show(sb.ToString());
            File.WriteAllText(@"c:\" + name + "Model.cs", sb.ToString());
            MessageBox.Show("导出成功啦");
        } 
        #endregion

        #region 2.生成DAL 类代码   public void CreateDAL(string name)
        /// <summary>
        /// 生成DAL 类代码
        /// </summary>
        /// <param name="name"></param>
        public void CreateDAL(string name)
        {
            string connStr = txtConnStr.Text;

            DataTable cols = SqlHelper.ExecuteDataTable(connStr, "select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@name",
                new SqlParameter("@name", name));

            //name表的列数
            string[] col = new string[cols.Rows.Count];
            for (int i = 0; i < cols.Rows.Count; i++)
            {
                DataRow row = cols.Rows[i];
                string colName = (string)row["COLUMN_NAME"];
                col[i] = colName;
            }

            //为每个列添加@做成parameter
            string[] parameter = new string[cols.Rows.Count];
            for (int i = 0; i < parameter.Length; i++)
            {
                DataRow row = cols.Rows[i];
                string paraCol = (string)row["COLUMN_NAME"];
                parameter[i] = "@" + paraCol;
            }



            StringBuilder sb = new StringBuilder();
            //生成类代码
            sb.AppendLine("class " + name + "DAL");
            sb.AppendLine("{");
            //类里的方法体
            //添加信息

            //将DataRow转成实体类对象
            #region 将DataRow转成实体类对象
            sb.AppendLine("public " + name + "Model To" + name + "(DataRow row)");
            sb.AppendLine("{");
            sb.AppendLine(name + "Model " + name + " = new " + name + "Model()");
            foreach (DataRow row in cols.Rows)
            {
                string colName = (string)row["COLUMN_NAME"];
                string dataType = (string)row["DATA_TYPE"];
                switch (dataType)
                {
                    case "uniqueidentifier":
                        dataType = "Guid";
                        break;
                    case "nvarchar":
                        dataType = "string";
                        break;
                    default:
                        dataType = "object";
                        break;
                }
                if ((string)row["IS_NULLABLE"] != "YES")
                {
                    dataType = dataType + "?";
                }
                sb.AppendLine(name + "." + colName + " = (" + dataType + ")row[\"" + colName + "\"];");
            }
            sb.AppendLine("return " + name);
            sb.AppendLine("}"); 
            #endregion
            sb.AppendLine();
            
            //sb.AppendLine("public int AddNew(" + name + "Model model){");
            //sb.AppendLine("int i = SqlHelper.ExecuteNonQuery(");
            //sb.AppendLine("\"insert into " + name + "(" + string.Join(",", col) + ") values (" + string.Join(",", parameter) + ")\",");
            //for (int i = 0; i < colNames.Rows.Count; i++)
            //{
            //    sb.AppendLine("new SqlParameter(\"" + parameter[i] + "\",model." + col[i] + ")");
            //}
            //sb.AppendLine(")");
            //sb.AppendLine("return i");
            //sb.AppendLine("}");

            //sb.AppendLine(""); 


            sb.AppendLine();

            //软删除
            #region 软删除
            sb.AppendLine("public int SoftDel(int id)");
            sb.AppendLine("{");
            sb.AppendLine("SqlHelper.ExecuteNonQuery(");
            sb.AppendLine("update " + name + " set IsDel = 1 where Id = @id,");
            sb.AppendLine("new SqlParameter(\"@id\",id))");
            sb.AppendLine("}"); 
            #endregion
            sb.AppendLine();

            //AddNew
            #region AddNew
            sb.AppendLine("public int AddNew(" + name + "Model model)");
            sb.AppendLine("{");
            sb.AppendLine("return SqlHelper.ExecuteNonQuery(@\"insert into " + name + "(");
            for (int i = 0; i < col.Length; i++)
            {
                if (i < col.Length - 1)
                {
                    sb.Append(col[i] + ",");
                }
                else
                {
                    sb.AppendLine(col[i] + ")");
                }

            }
            sb.AppendLine("values (");
            for (int i = 0; i < parameter.Length; i++)
            {
                if (i < parameter.Length - 1)
                {
                    sb.Append(parameter[i] + ",");
                }
                else
                {
                    sb.AppendLine(parameter[i] + ")\",");
                }
            }
            for (int i = 0; i < col.Length; i++)
            {
                if (i < col.Length - 1)
                {
                    sb.AppendLine("new SqlParameter(\"@" + col[i] + "\",model." + col[i] + "),");
                }
                else
                {
                    sb.AppendLine("new SqlParameter(\"@" + col[i] + "\",model." + col[i] + "));");
                }
            }

            sb.AppendLine("}"); 
            #endregion

            //ListAll 
            #region ListAll 
            sb.AppendLine("public " + name + "Model[] ListAll()");
            sb.AppendLine("{");
            sb.AppendLine("DataTable table = SqlHelper.ExecuteDataTable(\"select * from " + name + "\");");
            sb.AppendLine("if(table.Rows.Count<=0)");
            sb.AppendLine("{ return null;}");
            sb.AppendLine("else");
            sb.AppendLine("{");
            sb.AppendLine(name + "Model[] " + name + " = new " + name + "Model[table.Rows.Count];");
            sb.AppendLine("for(int i=0;i<table.Rows.Count;i++){");
            sb.AppendLine(name + "Model model = To" + name + "(table.Row[i]);");
            sb.AppendLine(name + "[i] = model");
            sb.AppendLine("}");
            sb.AppendLine("return " + name); 
            #endregion

            sb.AppendLine("public int Update(" + name + "Model model)");
            sb.AppendLine("{");
            sb.AppendLine("return SqlHelper.ExecuteNonQuery(@\"update " + name + " set ");
            for (int i = 1; i < col.Length; i++)
            {
                string colName = col[i];
                string paracolName = "@" + colName;
                if (i != col.Length - 1)
                {
                    sb.Append(colName + "=" + paracolName+",");
                }
                else
                {
                    sb.AppendLine(colName + "=" + paracolName + " where "+col[0]+"=@"+col[0]+"\",");
                }
            }
            for (int i = 0; i < col.Length; i++)
            {
                string parameterCol = "@" + col[i];
                if (i != col.Length - 1)
                {
                    sb.AppendLine("new SqlParameter(\"" + parameterCol + "\",model." + col[i]+"),");
                }
                else
                {
                    sb.AppendLine("new SqlParameter(\"" + parameterCol + "\",model." + col[i] + "));");
                }
            }
            sb.AppendLine("}");

            sb.AppendLine("}");
            File.WriteAllText("c:/" + name + "DAL.cs", sb.ToString());
            MessageBox.Show("OK");

        } 
        #endregion

        #region *.连接数据库  private void ConnetSQL()
        /// <summary>
        /// 连接数据库
        /// </summary>
        private void ConnetSQL()
        {
            string connStr = txtConnStr.Text;
            string sql = "select * from INFORMATION_SCHEMA.TABLES";
            DataTable table = SqlHelper.ExecuteDataTable(connStr, sql);
            foreach (DataRow row in table.Rows)
            {
                string tableName = Convert.ToString(row["TABLE_NAME"]);
                clbTable.Items.Add(tableName);
            }
            txtConnStr.ReadOnly = true;
        } 
        #endregion

        #region *.数据库数据类型 与 C#数据类型进行转换   public string ToDataType(string datatype)
        /// <summary>
        /// *.数据库数据类型 与 C#数据类型进行转换
        /// </summary>
        /// <param name="datatype"></param>
        /// <returns></returns>
        public string ToDataType(string datatype)
        {
            switch (datatype)
            {
                case "int":
                    return "int";
                case "nvarchar":
                case "varchar":
                case "char":
                case "nchar":
                    return "string";
                case "bit":
                    return "bool";
                case "decimal":
                    return "double";
                default:
                    return "object";
            }
        } 
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (string tableName in clbTable.CheckedItems)
            {
                CreateBLL(tableName);
            }
        }

        public void CreateBLL(string name)
        {

        }


    }
}
